#include "../Server/Server.h"

//服务端处理信息，将字符换变为大写
void StrToUpper(char* str,int len)
{
  for(int i=0;i<len ;i++)
  {
    str[i]=toupper(str[i]);
  }
}
//服务端处理信息，将字符换变为小写
void StrToLower(char* str,int len)
{
  for(int i=0;i<len ;i++)
  {
    str[i]=tolower(str[i]);
  }
}

void ServerAPI()
{
  //加载Windows环境
  WORD ver = MAKEWORD(2, 2);
  WSADATA dat;
  WSAStartup(ver, &dat);
  
  //创建socket
  SOCKET Server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  sockaddr_in Server_sin = {};
  Server_sin.sin_family = AF_INET;
  Server_sin.sin_port = htons(SERVER_PORT);
  //Server_sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //INADDR_ANY为默认地址
  //将十进制SERVER_IP转化为二进制保存至Server_sin.sin_addr中
  inet_pton(AF_INET, SERVER_IP, &Server_sin.sin_addr);

  //调用bind，将服务端本地地址到socket上
  if (SOCKET_ERROR == bind(Server_sock, (sockaddr*)&Server_sin, sizeof(Server_sin)))
  {
    printf("Bind failed!!!\n");
  }
  else {
    printf("Bind successful...\n");
  }

  //调用listen函数进行监听
  if (SOCKET_ERROR == listen(Server_sock, 5))
  {
    printf("Listen failed!!!\n");
  }
  else {
    printf("Listen successful...\n");
  }
  //调用accept接收客户端连接申请，并将客户端信息保存至Client_sin中
  sockaddr_in Client_sin = {};
  char IPdotdec[20];
  int nAddrLen = sizeof(sockaddr_in);

  SOCKET Client_sock = INVALID_SOCKET;
  Client_sock = accept(Server_sock, (sockaddr*)&Client_sin, &nAddrLen);
  if (Client_sock == INVALID_SOCKET)
  {
    printf("Accept Client_sin failed!!!\n");
  }
  else
  {
    printf("Accept clirntAddr successful... Sock = %d,IP = %s \n", (int)Client_sock, inet_ntop(AF_INET, &Client_sin.sin_addr, IPdotdec, 16));
  }

  char sendError[127]="The message is error!!!";
  char _recvBuf[128] = {};
  while (true)
  {
    //调用recv函数接收客户端发送的信息
    int nLen = recv(Client_sock, _recvBuf, 128, 0);
    if (nLen <= 0) {
      printf("Recv client's message failed!!!\n");
      break;
    }
    printf("Recv successful...");
    
    //根据接收到的信息，进行处理，并调用send返回对应的处理信息
    DataPackage* dp= (DataPackage*)_recvBuf;
    if(dp->dealMode==1){
      StrToUpper(dp->str,strlen(dp->str));
      send(Client_sock, (const char*)dp->str, strlen(dp->str), 0);
      printf("11");
    }
    else if(dp->dealMode==2){
      StrToLower(dp->str,strlen(dp->str));
      send(Client_sock, (const char*)dp->str, strlen(dp->str), 0);
    }
    else{
      send(Client_sock, (const char*)sendError, strlen(sendError), 0);
    }
  }

  //当客户端断开连接后，会关闭客户端
  closesocket(Server_sock);
  //
  WSACleanup();
  printf("Sever closed ...");
}